const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//返回月日
function dateformat(str){
	//var dateStr = '2017-10-22';
	var reg = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
	str.match(reg);
	return RegExp.$2+'-'+RegExp.$3;
	/*console.log(RegExp.$1);
	console.log(RegExp.$2);
	console.log(RegExp.$3);*/
}

function CurentTime()
{ 
    var now = new Date();
    
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    
    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ss = now.getSeconds();           //秒
    
    var clock = year + "-";
    
    if(month < 10)
        clock += "0";
    
    clock += month + "-";
    
    if(day < 10)
        clock += "0";
        
    clock += day + " ";
    
    if(hh < 10)
        clock += "0";
        
    clock += hh + ":";
    if (mm < 10) clock += '0'; 
    clock += mm + ":"; 
     
    if (ss < 10) clock += '0'; 
    clock += ss; 
    return(clock); 
}

function getRandom(m,n){
	return (Math.random()*(n-m) + m);
}

function isPoneAvailable(str) {  
    var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;  
    if (!myreg.test(str)) {  
        return false;  
    } else {  
        return true;  
    }  
}

function isPasswd(str){
	var strkong =/^[0-9a-zA-Z_]{8,14}$/g;
	if (!strkong.test(str)) { 
        return false;  
    } else {  
        return true;  
    } 
}

function isIdentity(str){
    var reg = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;
    if(reg.test(str)){
        return true;
    }else{
        return false;
    }
}

function isEmail(str){
	var myReg=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
	if(myReg.test(str)){
		return true;
	}else{
		return false;
	}
}

function isIntNum(val){
	//var re = /^\d+(?=\.{0,1}\d+$|$)/ ;
	//var re = /^((?!0)\d+(\.\d{1,1})?)$/ ;//整数不能是0，小数点保留一位小数
	var re = /^(\d+(\.\d{1,1})?)$/ ;//小数点保留一位小数
    if(re.test(val)){
        return true;
    }else{
        return false;
    }
}


function showShareMenu (){
	wx.showShareMenu({
 	   //withShareTicket: true
	});
}

function showError(str){
	wx.showModal({
        title: '提示',
		content: str,
		showCancel:false,
		success: function(res) {
		    if (res.confirm) {
		    }
		}
    })
}

function showSuccess(str){
	wx.showToast({
        title: str,
        icon: 'succes',
        duration: 1000,
        mask:true
    })
}


function showInfo(str,sucFun,showCancel){
	showCancel = showCancel || false;
	wx.showModal({
        title: '提示',
		content: str,
		showCancel:showCancel,
		success: sucFun
    })
}

function showLoading(str){
	wx.showToast({
        title: str,
        icon: 'loading'
    });
}

function closeLoading(){
	wx.hideToast();
}

function wxshowLoading(title,mask){
	title = title || '加载中...';
	mask = mask || true;
	wx.showLoading({
        title: title,
        mask:mask
    })
}

function wxhideLoading(){
	wx.hideLoading()
}

function setStorage(key,data){
	wx.setStorage({
		key: key,
		data: data,
	})
}
function getStorage(key) {
	return wx.getStorageSync(key);
}

function removeStorage(key){
	wx.removeStorage({
		key: key
	})
}

function RndNum(n){
    var rnd="";
    for(var i=0;i<n;i++)
        rnd+=Math.floor(Math.random()*10);
    return rnd;
}

function uploadImage(count,imageSrc,fileUrl){
	wx.chooseImage({
	      count: count,
	      sizeType: ['original', 'compressed'],
	      sourceType: ['album', 'camera'],
	      success: function(res){
	    	  console.log(res.tempFilePaths);
	    	  var tempFilePaths = res.tempFilePaths;
	          var successUp = 0; //成功个数
	          var failUp = 0; //失败个数
	          var length = res.tempFilePaths.length; //总共个数
	          var i = 0; //第几个
	          if(length>count){
	        	  showError('超出最大上传数');
	        	  return false;
	          }
	          showLoading('上传中');
	          uploadDIY(tempFilePaths,successUp,failUp,i,length,imageSrc,fileUrl);
	       }
	})
}


function uploadDIY(filePaths,successUp,failUp,i,length,imageSrc,fileUrl){
	      //var SERVER_URL = 'https://yituonongfu.ftxcx.net/fengteng.php?r=api/data&action=uploadImage';
	      var SERVER_URL = '';
	      //wx.toastShow(0,"图片上传中...",20000000,1);
	      wx.uploadFile({
	          url: SERVER_URL, 
	          filePath: filePaths[i],
	          name: 'file',
	          success: function(res){
	              successUp++;
	              var data = res.data;  
	              data=data.split("<br>");//将返回的字符串切割成数组  
	              var obj_setData={  
	                file:{  
	                  name:data[0],//文件名称  
	                  types:data[1],//文件类型  
	                  size:data[2]//文件大小  
	                }  
	              }
	              //console.log(obj_setData);   
	              //pageHandle.setData(obj_setData);//将返回的数据显示到界面上  
	              //console.log(data);
	              //console.log(obj_setData.file.name);
	              var info = JSON.parse(obj_setData.file.name);
	              console.log(info.filePath);
	              /*console.log(imageSrc.length);
	              if(imageSrc.length>count-1){
	            	  showError('超出最大上传数');
		        	  return false;
	              }*/
	              imageSrc.push(filePaths[i]);
	              fileUrl.push(info.filePath);
	              /*that.setData({
	            	  imageSrc : imageSrc,
		              fileUrl : fileUrl
		          });*/  

	          },
	          fail: (res) => {
	              failUp ++;
	          },
	          complete: () => {
	              i ++;                        
	              if(i == length){
	                //wx.hideToast();
	                var txt = '总共'+successUp+'张上传成功,'+failUp+'张上传失败！';
	                console.log(txt);
	                setStorage("imageSrc",imageSrc);
	                setStorage("fileUrl",fileUrl);
	                //app.toastShow(0,txt,2000,1);
	              }else{  //递归调用uploadDIY函数
	                uploadDIY(filePaths,successUp,failUp,i,length,imageSrc,fileUrl);
	              }
	          }
	      });
}


function getCurDate()
{
 var d = new Date();

 var years = d.getFullYear();
 var month = add_zero(d.getMonth()+1);
 var days = add_zero(d.getDate());
 var ndate = years+"-"+month+"-"+days;
 return ndate;
}


function add_zero(temp){
 if(temp<10) return "0"+temp;
 else return temp;
}

function plusXing (str,frontLen,endLen) { 
	var len = str.length-frontLen-endLen;
	var xing = '';
	for (var i=0;i<len;i++) {
		xing+='*';
	}
	return str.substring(0,frontLen)+xing+str.substring(str.length-endLen);
}

function isBlank(str){
	  if (Object.prototype.toString.call(str) ==='[object Undefined]'){//空
	    return true
	  } else if (
	    Object.prototype.toString.call(str) === '[object String]' || 
	    Object.prototype.toString.call(str) === '[object Array]') { //字条串或数组
	    return str.length==0?true:false
	  } else if (Object.prototype.toString.call(str) === '[object Object]') {
	    return JSON.stringify(str)=='{}'?true:false
	  }else{
	    return true
	  }

}

function priviewImg(e,that){
	var current = e.target.dataset.src;
    wx.previewImage({  
        current: current, // 当前显示图片的http链接  
        urls: that.data.previewList // 需要预览的图片http链接列表
    }) 
}

function compareDate(checkStartDate, checkEndDate) {
    var arys1= new Array();      
    var arys2= new Array();      
    if(checkStartDate != null && checkEndDate != null) {      
    	arys1=checkStartDate.split('-');
    	var sdate=new Date(arys1[0],parseInt(arys1[1].replace(/\b(0+)/gi,"")-1),arys1[2].replace(/\b(0+)/gi,""));      
    	arys2=checkEndDate.split('-');      
    	var edate=new Date(arys2[0],parseInt(arys2[1].replace(/\b(0+)/gi,"")-1),arys2[2].replace(/\b(0+)/gi,""));
		if(sdate > edate) {   
			showError("日期开始时间不能大于结束时间");         
		    return false;         
		}  else {   
		    return true;     
		}   
    }
}   

/**
 * author:zhuojiyun
 * version:1.0.0
 * **/
/*** 
 * 按照显示图片的宽等比例缩放得到显示图片的高 
 * @params originalWidth 原始图片的宽 
 * @params originalHeight 原始图片的高 
 * @params imageWidth   显示图片的宽，如果不传就使用屏幕的宽 
 * 返回图片的宽高对象 
***/
function imageZoomHeightUtil(originalWidth, originalHeight, imageWidth) {
  let imageSize = {};
  if (imageWidth) {
    imageSize.imageWidth = imageWidth;
    imageSize.imageHeight = (imageWidth * originalHeight) / originalWidth;
  } else {//如果没有传imageWidth,使用屏幕的宽 
    wx.getSystemInfo({
      success: function (res) {
        imageWidth = res.windowWidth;
        imageSize.imageWidth = imageWidth;
        imageSize.imageHeight = (imageWidth * originalHeight) / originalWidth;
      }
    });
  }
  return imageSize;
}
/*** 
 * 按照显示图片的高等比例缩放得到显示图片的宽 
 * @params originalWidth 原始图片的宽 
 * @params originalHeight 原始图片的高 
 * @params imageHeight  显示图片的高，如果不传就使用屏幕的高 
 * 返回图片的宽高对象 
***/
function imageZoomWidthUtil(originalWidth, originalHeight, imageHeight) {
  let imageSize = {};
  if (imageHeight) {
    imageSize.imageWidth = (imageHeight * originalWidth) / originalHeight;
    imageSize.imageHeight = imageHeight;
  } else {//如果没有传imageHeight,使用屏幕的高 
    wx.getSystemInfo({
      success: function (res) {
        imageHeight = res.windowHeight;
        imageSize.imageWidth = (imageHeight * originalWidth) / originalHeight;
        imageSize.imageHeight = imageHeight;
      }
    });
  }
  return imageSize;
}


module.exports = {
  formatTime: formatTime,
  dateformat: dateformat,
  CurentTime:CurentTime,
  getRandom:getRandom,
  isPoneAvailable:isPoneAvailable,
  isPasswd:isPasswd,
  isIdentity:isIdentity,
  isEmail:isEmail,
  isIntNum:isIntNum,
  showShareMenu:showShareMenu,
  showError:showError,
  showSuccess:showSuccess,
  showInfo:showInfo,
  showLoading:showLoading,
  closeLoading:closeLoading,
  setStorage: setStorage,
  getStorage: getStorage,
  removeStorage:removeStorage,
  uploadImage:uploadImage,
  uploadDIY:uploadDIY,
  getCurDate:getCurDate,
  add_zero:add_zero,
  plusXing:plusXing,
  isBlank:isBlank,
  priviewImg:priviewImg,
  compareDate:compareDate,
  imageZoomHeightUtil: imageZoomHeightUtil,
  imageZoomWidthUtil: imageZoomWidthUtil,
  wxshowLoading:wxshowLoading,
  wxhideLoading:wxhideLoading,
  RndNum:RndNum
}
